#include "Font.h"

Font::Font() : m_pFont(NULL) {}

bool Font::Initialize(LPDIRECT3DDEVICE9 pDevice, char* faceName, int size, bool bold, bool italic) {
	SAFE_RELEASE(m_pFont);
	HRESULT hr;

	hr = D3DXCreateFont(pDevice, -size, 0, bold ? 800 : 0, 1, italic, DEFAULT_CHARSET, 
		OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, faceName, &m_pFont);
	if(FAILED(hr)) {
		SHOWERROR("D3DXCreateFont() failed.", __FILE__, __LINE__);
		return false;
	}
	return true;
}

void Font::print(char* text, int xPosition, int yPosition, DWORD color, LPD3DXSPRITE sprite, 
				int textBoxWidth, int textBoxHeight, FONT_ALIGNMENT alignment) {
	if (!m_pFont) {
		return;
	}
	DWORD format = DT_EXPANDTABS;
	if(textBoxWidth == 0) {
		format |= DT_NOCLIP;
	} else {
		format |= DT_WORDBREAK;
		switch (alignment) {
		case FA_LEFT:
			format |= DT_LEFT;
			break;
		case FA_CENTER:
			format |= DT_CENTER;
			break;
		case FA_RIGHT:
			format |= DT_RIGHT;
			break;
		case FA_TOPRIGHT:
			format |= DT_RIGHT | DT_TOP;
			break;
		case FA_BOTTOMRIGHT:
			format |= DT_RIGHT | DT_BOTTOM;
			break;
		case FA_TOPLEFT:
			format |= DT_LEFT | DT_TOP;
			break;
		case FA_BOTTOMLEFT:
			format |= DT_LEFT | DT_BOTTOM;
			break;
		}
		if (textBoxHeight == 0) {
			// a width is specified, but not a height
			// makes it seem like height is infinite
			textBoxHeight = 2000;
		}
	}
	RECT rect = {xPosition, yPosition, xPosition + textBoxWidth, yPosition + textBoxHeight};
	m_pFont->DrawText(sprite, text, -1, &rect, format, color);
}

void Font::OnLostDevice() {
	if(m_pFont) {
		m_pFont->OnLostDevice();
	}
}

void Font::OnResetDevice() {
	if(m_pFont) {
		m_pFont->OnResetDevice();
	}
}

void Font::Release() {
	SAFE_RELEASE(m_pFont); 
}
